package cn.qyd.threadsignal;

import javax.annotation.security.RunAs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.concurrent.Phaser;

/**
 * @author 邱运铎
 * @date 2024-03-25 13:35
 */
public class PhaseDemo01 {
    static class PreSourceTask implements Runnable {
        private String task;
        private Phaser phaser;

        public PreSourceTask(String task, Phaser phaser) {
            this.task = task;
            this.phaser = phaser;
        }
        @Override
        public void run() {
            Random random = new Random();
            for (int i = 1; i < 4; i++) {
                try {
                    if (i >= 2 && "加载新手教程".equals(task)) {
                        continue;
                    }
                    Thread.sleep(random.nextInt(3000));
                    System.out.println(String.format("第-%d-关卡需要加载-%d-个模块,当前模块--%s--已完成", i, phaser.getRegisteredParties(), task));
                    if (i == 1 && "加载新手教程".equals(task)) {
                        System.out.println("下次关卡移除加载【新手教程模块】");
                        phaser.arriveAndDeregister();
                    } else {
                        phaser.arriveAndAwaitAdvance();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        Phaser phaser = new Phaser(4) {
            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                System.out.println(String.format("第%d次关卡准备完成", phase + 1));
//                System.out.println("当前注册的任务数量： " + registeredParties);
//                return phase == 3 || registeredParties == 0;
                return super.onAdvance(phase,registeredParties);
            }
        };

        new Thread(new PreSourceTask("加载新手教程",phaser)).start();
        new Thread(new PreSourceTask("加载背景音乐",phaser)).start();
        new Thread(new PreSourceTask("加载地图模型数据",phaser)).start();
        new Thread(new PreSourceTask("加载人物模型数据",phaser)).start();
    }
}
